<!--
  * 工时功能
  *
  * @Author:    yjg
  * @Date:      2024-09-09 11:02:13
  * @Copyright  v1.0
-->
<template>
    <!-- 查询表单form begin -->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
			<a-form-item label="部门" name="departmentId" class="smart-query-form-item">
				<DepartmentTreeSelect ref="departmentTreeSelect" width="180px" :init="false" v-model:value="departmentId" @change="departmentChange"/>
			</a-form-item>
			<a-form-item label="人员选择" name="memberIdList" class="smart-query-form-item" >
			   <a-select mode="multiple" v-model:value="checkedMemberId" style="width: 200px" @change="employeeChange" optionFilterProp="title" placeholder="请人员选择">
			   <a-select-option v-for="item in memberList" :key="item.loginName"  :title="item.actualName">{{ item.actualName }}</a-select-option>
			   </a-select>
			</a-form-item>
			<a-form-item label="班别类型" name="banbieType" class="smart-query-form-item">
			  <DictSelect key-code="BANBIE_TYPE" v-model:value="queryForm.banbieType" width="120px" />
			</a-form-item>
			<a-form-item label="加班类型" name="banbieType" class="smart-query-form-item">
			  <DictSelect key-code="OVERTIM_TYPE" v-model:value="queryForm.overtimeType" width="120px" />
			</a-form-item>
			<a-form-item label="审批类型" name="allowFlag" class="smart-query-form-item">
			  <DictSelect key-code="ALLOW_STATUS" v-model:value="queryForm.allowFlag" width="120px" />
			</a-form-item>
			<a-form-item label="工作日期" class="smart-query-form-item">
			  <a-space direction="vertical" :size="12">
			    <a-range-picker v-model:value="searchDate" :presets="defaultTimeRanges" @change="dateChange" />
			  </a-space>
			</a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="queryData">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!-- 查询表单form end -->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!-- 表格操作行 begin -->
        <a-row class="smart-table-btn-block">
			<div class="smart-table-operate-block">
				<a-button @click="exportExcel(1)" type="primary">
				    <template #icon>
				        <FileExcelOutlined />
				    </template>
				    工时月结
				</a-button>
				<a-button @click="exportExcel(2)" type="primary">
				    <template #icon>
				        <FileExcelOutlined />
				    </template>
				    工时加班
				</a-button>
				<a-button @click="confirmBatchApprove()" type="primary"  :disabled="selectedRowKeyList.length === 0">
				    <template #icon>
				        <CheckCircleOutlined />
				    </template>
				    审批
				</a-button>
			</div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!-- 表格操作行 end -->

        <!-- 表格 begin -->
        <a-table
                size="small"
                :dataSource="tableData"
                :columns="columns"
                rowKey="workingHoursId"
                bordered
                :loading="tableLoading"
                :pagination="false"
                :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
            <template #bodyCell="{ text, record, column }">
				<template v-if="column.dataIndex === 'banbieType'">
				  <span>{{ text && text.length > 0 ? text[0].valueName : '' }}</span>
				</template>
				<template v-else-if="column.dataIndex === 'overtimeType'">
				  <span>{{ text && text.length > 0 ? text[0].valueName : '' }}</span>
				</template>
				<template v-else-if="column.dataIndex === 'allowFlag'">
				  <span>{{ text ==1 ? '审批通过' : (text ==2 ? '驳回':text ==3 ? '撤销' : (text ==2 ? '不通过':'')) }}</span>
				</template>
                <template v-else-if="column.dataIndex === 'action'">
					<div class="smart-table-operate">
					    <a-button   type="link" 
						v-if="record.allowFlag == 1"
						>已审批</a-button>
						<a-button @click="allowForm(record,false)" type="link"
						v-if="record.allowFlag === 0 || record.allowFlag ==3"
						>审批</a-button>
						<a-button @click="showForm(record)" type="link"
						v-if="record.allowFlag === 0 || record.allowFlag ==1"
						>编辑</a-button>
						<a-button @click="allowForm(record,true)" type="link"
						v-if="record.allowFlag === 2 "
						>撤销</a-button>
					</div>
                </template>
            </template>
        </a-table>
        <!-- 表格 end -->

        <div class="smart-query-table-page">
            <a-pagination
                    showSizeChanger
                    showQuickJumper
                    show-less-items
                    :pageSizeOptions="PAGE_SIZE_OPTIONS"
                    :defaultPageSize="queryForm.pageSize"
                    v-model:current="queryForm.pageNum"
                    v-model:pageSize="queryForm.pageSize"
                    :total="total"
                    @change="queryData"
                    @showSizeChange="queryData"
                    :show-total="(total) => `共${total}条`"
            />
        </div>
        <CategoryFormModal  ref="formRef" @reloadList="queryData"/>
		<EditFormModal  ref="formEditRef" @reloadList="queryData"/>
    </a-card>
</template>
<script setup>
    import { reactive, ref, onMounted } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { workingHoursApi } from '/@/api/business/working-hours/working-hours-api';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
	import DictSelect from '/@/components/support/dict-select/index.vue';
	import CategoryFormModal from './components/working-hours-form-allow.vue';
	import EditFormModal from './components/working-hours-form-allow-edit.vue';
	import { defaultTimeRanges } from '/@/lib/default-time-ranges';
	import { employeeApi } from '/@/api/system/employee-api';
	import DepartmentTreeSelect from '/@/components/system/department-tree-select/department.vue';
    // ---------------------------- 表格列 ----------------------------

    const columns = ref([
		{
		    title: '工号',
		    dataIndex: 'jobNumber',
		    ellipsis: true,
			width: '70px', // 可以自定义宽度
			sorter: {
			  compare: (a, b) => a.jobNumber - b.jobNumber,
			  multiple: 3,
			},
		},
        {
            title: '姓名',
            dataIndex: 'name',
            ellipsis: true,
        },
		{
            title: '部门名称',
            dataIndex: 'deptName',
            ellipsis: true,
        },
        {
            title: '工作日期',
            dataIndex: 'overtimeData'
        },
        {
            title: '班别类型',
            dataIndex: 'banbieType'
        },
        {
            title: '加班类型',
            dataIndex: 'overtimeType',
            ellipsis: true,
        },
        {
            title: '建议加班1',
            dataIndex: 'timeparams1',
            ellipsis: true,
        },
        {
            title: '建议加班2',
            dataIndex: 'timeparams2',
            ellipsis: true,
        },
        {
            title: '建议加班3',
            dataIndex: 'timeparams3',
            ellipsis: true,
        },
		{
		    title: '时数',
		    dataIndex: 'overtimeNumber2',
		    ellipsis: true,
			width: '50px', // 可以自定义宽度
		},
        {
            title: '加班原因',
            dataIndex: 'overtimeResult',
            ellipsis: true,
        },
		{
		    title: '创建者姓名',
		    dataIndex: 'createUserName',
		    ellipsis: true,
		},
        {
            title: '审批状态',
            dataIndex: 'allowFlag',
            ellipsis: true,
        },
        {
            title: '审批时间',
            dataIndex: 'allowTime',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: 110,
        },
    ]);
	
	// --------------------------- 导出 ---------------------------
	async function exportExcel(value) {
		 if(queryForm.startTime == null || queryForm.endTime == null){
		 	message.error('请选择工作日期');
		 }else{
			 queryForm.excelFlag = value
			 await workingHoursApi.exportExcel(queryForm);
		 }
	}
    // ---------------------------- 查询数据表单和方法 ----------------------------
	// 日期选择
	let searchDate = ref();
	
	function dateChange(dates, dateStrings) {
		
	  queryForm.startTime = dateStrings[0];
	  queryForm.endTime = dateStrings[1];
	}

    const queryFormState = {
        pageNum: 1,
        pageSize: 15,
		endTime: null,
		startTime: null,
		banbieType: null,
		overtimeType: null,
		excelFlag: null,
		overtimeFlag: 0,
		departmentIds: null,
		checkedMemberNumbers: null,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);
	// 部门选择
	let departmentId = ref();
	//人员列表
	const memberList = ref([]); 
	//选中人员列表
	const checkedMemberId = ref([]);

    // 重置查询条件
    function resetQuery() {
		searchDate.value = [];
		departmentId.value = [];
		checkedMemberId.value = [];
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }
	
	//部门选择
	async function departmentChange(departments,departmentString){
	   queryForm.departmentIds = departments 
	   try{
		  checkedMemberId.value = [];
		  memberList.value = null;
		  if(queryForm.departmentIds ==null || queryForm.departmentIds.length === 0){
			let queryResult = await employeeApi.queryAll()
			memberList.value = queryResult.data
		  }else{
			let queryResult = await employeeApi.queryEmployeeByDeptIds(queryForm.departmentIds)
			memberList.value = queryResult.data  
		  }    
	   }catch(e){
	   	  smartSentry.captureError(e);
	   } finally {
	       
	   }
	}
	//人员选择
	function employeeChange(employees,employeesString){
		queryForm.checkedMemberNumbers = employees;
	}
	//查询人员数据
	async function handleEmployee(){
		try{
			memberList.value = null;
			let queryResult = await employeeApi.queryAll()
			memberList.value = queryResult.data
		  }catch(e){
			smartSentry.captureError(e);
		  } finally {
	        tableLoading.value = false;
	    }
	}

    // 查询数据
    async function queryData() {
		handleEmployee();
		if((queryForm.banbieType+1) == '1'){
			queryForm.banbieType = null;
		}
		if((queryForm.overtimeType+1) == '1'){
			queryForm.overtimeType = null;
		}
		if((queryForm.allowFlag+1) == '1'){
			queryForm.allowFlag = null;
		}
        tableLoading.value = true;
        try {
            let queryResult = await workingHoursApi.queryAllowPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }

    onMounted(queryData);
    // ---------------------------- 审批 ----------------------------
    //确认审批
	const formRef = ref();
    function allowForm(data,flag){
		formRef.value.show(data,flag);
    }
	
	//--------------------------------编辑-----------------------------------
	
	const formEditRef = ref();
	function showForm(data) {
		let overtimeFlag = 0; //0代表工时审批
	    formEditRef.value.show(data,overtimeFlag);
	}
	
	// ---------------------------- 批量审批 ----------------------------
	
	// 选择表格行
	const selectedRowKeyList = ref([]);
	
	function onSelectChange(selectedRowKeys) {
	    selectedRowKeyList.value = selectedRowKeys;
	}
	
	// 批量删除
	function confirmBatchApprove() {
	    Modal.confirm({
	        title: '提示',
	        content: '确定要批量审批这些数据吗?',
	        okText: '审批',
	        okType: 'danger',
	        onOk() {
	            requestBatchApprove();
	        },
	        cancelText: '取消',
	        onCancel() {},
	    });
	}
	
	//请求批量审批
	async function requestBatchApprove() {
	    try {
	        SmartLoading.show();
	        await workingHoursApi.batchApprove(selectedRowKeyList.value);
	        message.success('审批成功');
	        queryData();
	    } catch (e) {
	        smartSentry.captureError(e);
	    } finally {
	        SmartLoading.hide();
	    }
	}
</script>
